﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace ThoiTrangT2B.Admin
{
    public partial class CapNhatKhohang : System.Web.UI.Page
    {
        private static int ProductID;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["pID"] != null)
                {
                    ProductID = Convert.ToInt32(Request.QueryString["pID"]);
                    LoadSanPham(ProductID);
                    LoadListSanPhamChiTiet(ProductID);
                    LoadColor();
                }
            }
        }

        private void LoadColor()
        {
            string sql = "SELECT * FROM dbo.tblT2BDanhMuc WHERE MaDM = 'cl'";
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
            dtlMauSac.DataSource = dt;
            dtlMauSac.DataBind();
        }

        private void LoadSanPham(int pID)
        {
            string sql = "SELECT TOP 1 * FROM dbo.tblT2BSanPham WHERE ID = @ID";
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, pID));
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql, arrParams);
            IMGSanPham.ImageUrl = "../" + dt.Rows[0]["Image"].ToString();
            TenSanPham.Text = dt.Rows[0]["TenSP"].ToString();
            MaSanPham.Text = dt.Rows[0]["MaSP"].ToString();
            GiaSanPham.Text = "Giá : " + Convert.ToInt32(dt.Rows[0]["Gia"]).ToString("###,###") + " VNĐ";
            GiaKhuyenMai.Text = "Giá khuyến mãi : " + (Convert.ToInt32(dt.Rows[0]["Gia"]) - (Convert.ToInt32(dt.Rows[0]["Gia"]) * Convert.ToInt32(dt.Rows[0]["KM"]) / 100)).ToString("###,###") + " VNĐ";
        }

        protected void LoadListSanPhamChiTiet(int pID)
        {
            string sql = "SELECT h.ID,h.SanPhamID,d1.TenDM AS MauSac,d2.TenDM AS Size,h.SL FROM dbo.tblT2BKhoHang h INNER JOIN dbo.tblT2BDanhMuc d1 ON h.ColorID_DM = d1.ID " +
                         "INNER JOIN dbo.tblT2BDanhMuc d2 ON h.SizeID_DM = d2.ID WHERE h.SanPhamID = @SanPhamID";
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@SanPhamID", SqlDbType.Int, ParameterDirection.Input, pID));
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql, arrParams);
            grvData.DataSource = dt;
            grvData.DataBind();

        }

        protected void grvData_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string sID = e.CommandArgument.ToString().Trim();
            string sCommandName = e.CommandName;
            if ((sCommandName == ThoiTrangT2B.MyConst.Action.Approve))
            {
                TextBox txtSoLuong = (TextBox)grvData.Rows[grvData.EditIndex].Cells[2].Controls[1];
                CapNhatSoLuong(Convert.ToInt32(sID), Convert.ToInt32(txtSoLuong.Text));
            }
            else if ((sCommandName == ThoiTrangT2B.MyConst.Action.Delete))
            {
                string sql = "Select NoiDung from tblT2BWebContent where ID = " + sID;
                DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
                string FileName = dt.Rows[0]["NoiDung"].ToString();
                sql = "DELETE FROM dbo.tblT2BWebContent WHERE ID = " + sID;
                SqlHelper.ExecuteNonQuery(CommandType.Text, sql);
                try
                {
                    File.Delete(Server.MapPath("../" + FileName));
                }
                catch (Exception ex)
                {
                    Response.Write(ex.StackTrace);
                }


            }
            grvData.EditIndex = -1;
            LoadListSanPhamChiTiet(ProductID);
        }

        private void CapNhatSoLuong(int khohangID, int SL)
        {
            string sql = "UPDATE dbo.tblT2BKhoHang SET SL = @SL WHERE ID = @ID";
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@SL", SqlDbType.Int, ParameterDirection.Input, SL));
            arrParams.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, khohangID));
            SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
        }

        protected void grvData_RowEditing(object sender, GridViewEditEventArgs e)
        {
            grvData.EditIndex = e.NewEditIndex;
            LoadListSanPhamChiTiet(ProductID);
        }

        protected void grvData_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grvData.EditIndex = -1;
            LoadListSanPhamChiTiet(ProductID);
        }

        protected void grvData_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            grvData.DeleteRow(e.RowIndex);
            grvData.DataBind();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            ThemDacTinhSanPham(ProductID);
            LoadListSanPhamChiTiet(ProductID);
        }

        private void ThemDacTinhSanPham(int idenNumber)
        {
            string sql = "INSERT INTO dbo.tblT2BKhoHang(SanPhamID,SizeID_DM,ColorID_DM,Image,SL,CreateDate) " +
                         "VALUES(@SanPhamID,@SizeID_DM,@ColorID_DM,@Image,0,GETDATE())";
            List<SqlParameter> arrParams = new List<SqlParameter>();
            foreach (DataListItem li in dtlMauSac.Items)
            {
                CheckBox chkColor = (CheckBox)li.FindControl("chkColor");
                HiddenField hdnID = (HiddenField)li.FindControl("hdnID");
                CheckBoxList cbl = (CheckBoxList)li.FindControl("chkSizeList");
                FileUpload fulImage = (FileUpload)li.FindControl("fulImage");
                if (chkColor.Checked)
                {
                    string ImageUrl = UploadFile(fulImage);
                    foreach (ListItem item in cbl.Items)
                    {
                        if (item.Selected)
                        {
                            if (CheckDacTinhSanPham(Convert.ToInt32(hdnID.Value), Convert.ToInt32(item.Value), idenNumber))
                            {
                                arrParams.Add(SqlHelper.CreateParameterObject("@SanPhamID", SqlDbType.Int, ParameterDirection.Input, idenNumber));
                                arrParams.Add(SqlHelper.CreateParameterObject("@SizeID_DM", SqlDbType.Int, ParameterDirection.Input, item.Value));
                                arrParams.Add(SqlHelper.CreateParameterObject("@ColorID_DM", SqlDbType.Int, ParameterDirection.Input, hdnID.Value));
                                arrParams.Add(SqlHelper.CreateParameterObject("@Image", SqlDbType.NVarChar, ParameterDirection.Input, ImageUrl));
                                SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
                                arrParams.Clear();
                            }
                        }
                    }
                }
            }
        }

        private string UploadFile(FileUpload ful)
        {
            try
            {
                if (ful.HasFile)
                {
                    string sFolderPath = Server.MapPath(@"../userfiles/product");
                    HttpPostedFile myFile = ful.PostedFile;
                    string sFileName = myFile.FileName;
                    string[] arrFileName = sFileName.Split('.');
                    arrFileName[0] = arrFileName[0] + "_" + DateTime.Now.ToString("ddMMyyhhssmm");
                    sFileName = arrFileName[0] + "." + arrFileName[1];

                    // Create a bitmap of the content of the fileUpload control in memory
                    Bitmap originalBMP = new Bitmap(ful.FileContent);

                    // Calculate the new image dimensions
                    float origWidth = originalBMP.Width;
                    float origHeight = originalBMP.Height;
                    float sngRatio;
                    if (origHeight > origWidth)
                    {
                        sngRatio = origHeight / origWidth;
                    }
                    else
                    {
                        sngRatio = origWidth / origHeight;
                    }
                    int newWidth = 650;
                    int newHeight = Convert.ToInt32(newWidth * sngRatio);

                    // Create a new bitmap which will hold the previous resized bitmap
                    Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);

                    // Create a graphic based on the new bitmap
                    Graphics oGraphics = Graphics.FromImage(newBMP);
                    // Set the properties for the new graphic file
                    oGraphics.SmoothingMode = SmoothingMode.AntiAlias; oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

                    // Draw the new graphic based on the resized bitmap
                    oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
                    // Save the new graphic file to the server
                    newBMP.Save(string.Format(@"{0}\{1}", sFolderPath, sFileName));

                    // Once finished with the bitmap objects, we deallocate them.
                    originalBMP.Dispose();
                    newBMP.Dispose();
                    oGraphics.Dispose();

                    //myFile.SaveAs(string.Format(@"{0}\{1}", sFolderPath, sFileName));
                    return "userfiles/product/" + sFileName;




                }
                else
                {
                    return "";
                }
            }
            catch (Exception)
            {
                return "";
            }
        }

        private bool CheckDacTinhSanPham(int color, int size, int IDSP)
        {
            string sql = "SELECT * FROM dbo.tblT2BKhoHang WHERE SizeID_DM = @SizeID_DM AND ColorID_DM = @ColorID_DM AND SanPhamID = @IDSP";
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@SizeID_DM", SqlDbType.Int, ParameterDirection.Input, size));
            arrParams.Add(SqlHelper.CreateParameterObject("@ColorID_DM", SqlDbType.Int, ParameterDirection.Input, color));
            arrParams.Add(SqlHelper.CreateParameterObject("@IDSP", SqlDbType.Int, ParameterDirection.Input, IDSP));
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql, arrParams);
            if (dt.Rows.Count == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        protected void dtlMauSac_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                CheckBoxList cbl = (CheckBoxList)e.Item.FindControl("chkSizeList");
                string sql = "SELECT * FROM dbo.tblT2BDanhMuc WHERE MaDM = 'size'";
                DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    cbl.Items.Add(new ListItem("Size " + dt.Rows[i]["TenDM"].ToString(), dt.Rows[i]["ID"].ToString()));
                }
            }
        }
    }
}
